//
//  XYEmoticonTool.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/7.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit

let XYEmoticonMaxCol = 7
let XYEmoticonMaxRow = 3
// 每页最多显示的表情数
let XYMaxEmoticonCountInPage = XYEmoticonMaxCol * XYEmoticonMaxRow - 1
class XYEmoticonTool: NSObject {
    
    private let recentEmoticonPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentemoticon.archive")
    
    // 单例
    static let sharedEmoticonTool: XYEmoticonTool = XYEmoticonTool()
    
    // 表情数据报
    lazy var emoticonBundle: NSBundle = {
        
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        return NSBundle(path: path)!
    }()
    /// 最近
    private lazy var recentEmoticons: [XYEmoticon] = {
        // 解档
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(self.recentEmoticonPath) as? [XYEmoticon]
        if result != nil {
            return result!
        }
        return [XYEmoticon]()
    }()
    /// 默认
    private lazy var defaultEmoticons: [XYEmoticon] = {
        return self.emoticonsWithPlistName("default/info.plist")
    }()
    /// emoji
    private lazy var emojiEmoticons: [XYEmoticon] = {
        return self.emoticonsWithPlistName("emoji/info.plist")
    }()
    /// 浪小花
    private lazy var LxhEmoticons: [XYEmoticon] = {
        return self.emoticonsWithPlistName("lxh/info.plist")
    }()
    
    
    // 所有表情数据的总数组
    lazy var allEmoticons: [[[XYEmoticon]]] = {
        
        return [
            
            self.pageArrayWithEmoticons(self.recentEmoticons),
            self.pageArrayWithEmoticons(self.defaultEmoticons),
            self.pageArrayWithEmoticons(self.emojiEmoticons),
            self.pageArrayWithEmoticons(self.LxhEmoticons)
        ]
    }()
    
    // 默认表情 108 个， 要分成里面表情最多20个的小数组
    
    /// 将传入的表情数组，分成20个一个小数组并一起返回
    private func pageArrayWithEmoticons(emoticons:[XYEmoticon]) -> [[XYEmoticon]] {
        
        // 每页20 个计算需要多少页
        let pageCount: Int = (emoticons.count - 1) / XYMaxEmoticonCountInPage + 1
        var result: [[XYEmoticon]] = [[XYEmoticon]]()
        
        for i in 0..<pageCount {
            // 开始截取的位置
            let location = i * XYMaxEmoticonCountInPage
            var lenth = XYMaxEmoticonCountInPage
            // 判断是否越界
            if location + lenth > emoticons.count {
                lenth = emoticons.count - location
            }
            let range = NSMakeRange(location, lenth)
            let subArray = (emoticons as NSArray).subarrayWithRange(range) as! [XYEmoticon]
            result.append(subArray)
        }
        return result
    }
    func emoticonWithChs(chs: String?) -> XYEmoticon? {
        
        if chs == nil {
            return nil
        }
        // 过滤数组中的元素 $0 代表第0 个参数
        if let result = defaultEmoticons.filter({ $0.chs == chs }).first {
            return result
        }
        if let result = LxhEmoticons.filter({ $0.chs == chs }).first {
            return result
        }
        return nil
    }
    /// 通过表情的路径，请求该表情的 info.plist 文件 字典转模型
    ///
    /// - parameter path: 表情 info.plist 文件的路径，比如 `default/info.plist`
    ///
    /// - returns: 表情数组
    private func emoticonsWithPlistName(plistName:String) -> [XYEmoticon] {
        
        let file = self.emoticonBundle.pathForResource(plistName, ofType: nil)!
        // 数组字典
        let emoticonInfoDictArray = NSArray(contentsOfFile: file)!
        
        // 遍历字典 字典转模型
        var resultArray = [XYEmoticon]()
        for dict in emoticonInfoDictArray {
            
            let emoticon = XYEmoticon(dict: dict as! [String : AnyObject])
            resultArray.append(emoticon)
            emoticon.path = (plistName as NSString).stringByDeletingLastPathComponent
        }
        return resultArray
    }
    
    // 保存最近表情
    func saveRecentEmoticon (emoticon:XYEmoticon) {
        
        // indexOf --> 系统默认会去数组里面找与传入的模型的地址值是否一样，
        // --> 在遍历时候调用对象身上的 isEqual 方法与你要 indexOf 的那个对象进行对比。super 默认比较的是地址值
        // 如果存在 先将之前的表情移除
        if let index = recentEmoticons.indexOf(emoticon) {
            recentEmoticons.removeAtIndex(index)
        }
        // 将表情插入到数组中
        recentEmoticons.insert(emoticon, atIndex: 0)
        // 判断 如果表情超过20个就移除
        while recentEmoticons.count > XYMaxEmoticonCountInPage {
            
            recentEmoticons.removeLast()
        }
        // 归档保存表情
        NSKeyedArchiver.archiveRootObject(recentEmoticons, toFile: recentEmoticonPath)
        allEmoticons[0][0] = recentEmoticons
        
    }

}
